using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

using Model;
using BLL.WWW_WWW.Wiki;
using Model.WWW_WWW.Wiki;

namespace BLF.WWW_WWW.Wiki
{
	/// <summary>
	/// Implements a Formatter Provider that allows to write multi-language content in Wiki Pages.
	/// </summary>
	[Serializable]
	public class MultilanguageContentPlugin {

		static private string defaultLanguage = "en-us";
        static private bool displayWarning = false;

        static private string divStyle = "padding: 2px; margin-bottom: 10px; font-size: 11px; background-color: #FFFFC4; border: solid 1px #DDDDDD;";
        static private string standardMessage = @"<div style=""" + divStyle + @""">The content of this Page is localized in your language. To change the language settings, please go to the <a href=""Language.aspx"">Language Selection</a> page.</div>";
        static private string notLocalizedMessage = @"<div style=""" + divStyle + @""">The content of this Page is <b>not</b> available in your language, and it is displayed in the default language of the Wiki. To change the language settings, please go to the <a href=""Language.aspx"">Language Selection</a> page.</div>";

        static public bool PerformPhase1
        {
			get { return false; }
		}

        static public bool PerformPhase2
        {
			get { return false; }
		}

        static public bool PerformPhase3
        {
			get { return true; }
		}

        static public string Format(string raw, PageInfo page)
        {
			string result = ExtractLocalizedContent(Lx.Web.Common.UI.Globals.Language, raw); // Try to load localized content
			bool notLocalized = false;
			bool noLocalization = false;
			if(result == null) {
				result = ExtractLocalizedContent(defaultLanguage, raw); // Load content in the default language
				notLocalized = true;
				noLocalization = false;
			}
			if(result == null) {
				result = raw; // The Page is not localized, return all the content
				notLocalized = false;
				noLocalization = true;
			}
            if (displayWarning && !noLocalization && page != null)
            {
				if(notLocalized) return notLocalizedMessage + result;
				else return standardMessage + result;
			}
			else return result;
		}

        static private string ExtractLocalizedContent(string language, string content)
        {
			string head = "\\<" + language + "\\>", tail = "\\<\\/" + language + "\\>";
			Regex regex = new Regex(head + "(.+?)" + tail, RegexOptions.IgnoreCase | RegexOptions.Singleline);
			Match match = regex.Match(content);
			StringBuilder sb = new StringBuilder();
			while(match.Success) {
				sb.Append(match.Groups[1].Value);
				match = regex.Match(content, match.Index + match.Length + 1);
			}
			if(sb.Length > 0) return sb.ToString();
			else return null;
		}

		public void Shutdown() { }

	}

}
